const {
  MemberModel
} = require('../../../../utils/member-model.js');
var memberModel = new MemberModel();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    labelData: [],
    selectKeyValue: [], //已选择的个人标签
    disabled: false,
    isHints: false
  },
  /**
   *  查询商户所有标签
   */
  getUserTags: function () {
    memberModel.userTags({
      merchantId: wx.getStorageSync('merchantId')
    }).then(data => {
      if (data && data.length > 0) {
        this.setData({
          labelData: data,
          isHints: false
        })
      } else {
        this.setData({
          labelData: [],
          isHints: true
        })
      }
    }).catch(err => {
      wx.showToast({
        title: `${err.error}`,
        icon: 'none',
        duration: 2000
      })
    })
  },


  /**
   * 选择标签
   */
  setSelectLabel(event) {
    var that = this;
    var index = event.currentTarget.dataset.index; //门店id
    var nowChoose = that.data.labelData[index].choose;
    that.setData({
      selectKeyValue: that.data.labelData.filter(item => item.choose == 1) || [], //已选择的标签
    }, function () {
      if (that.data.selectKeyValue.length < 5 || nowChoose == '1') {
        that.setData({
          ['labelData[' + index + '].choose']: nowChoose == '0' ? '1' : '0'
        })
      }
    })
  },

  /**
   * 选好了
   */
  setLabelData: function () {
    var that = this;
    that.setData({
      disabled: true,
      selectKeyValue: that.data.labelData.filter(item => item.choose == 1) || [], //已选择的标签
    }, function () {
      that.modifyPersonalInformation();
    })
  },

  /**
   * 修改个人信息
   */
  modifyPersonalInformation: function () {
    var that = this;
    var keyValue = "";
    for (var i = 0; i < that.data.selectKeyValue.length; i++) {
      var item = that.data.selectKeyValue[i];
      var icon = i < that.data.selectKeyValue.length - 1 ? ',' : ''
      keyValue += item.itemName + icon
    }
    var param = {}
    param.merchantId = wx.getStorageSync('merchantId');
    param.key = "tags";
    param.value = keyValue;
    memberModel.userUpdate(param).then(data => {
      that.setData({
        disabled: false,
      })
      wx.navigateBack({
        delta: 1
      })
    }).catch(err => {
      that.setData({
        disabled: false,
      })
      wx.showToast({
        title: `${err.error}`,
        icon: 'none',
        duration: 2000
      })
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getUserTags();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
})